import { defineComponent, toRefs } from 'vue'

/* http */
import * as qualityApi from '@src/api/intelligentQuality.js'
/* utils */
import { message, confirm } from '@src/util/message'
/* components */
import QualityItem from '@src/modules/intelligentQuality/components/qualityItem.tsx'

export default defineComponent({
    name: 'QualityCard',
    props: {
        loading: {
            type: Boolean,
            default: true
        },
        cardList: {
            type: Array,
            default: () => []
        }
    },
    emits: ['goDetail', 'delete', 'edit'],
    setup(props) {
        const {cardList} = toRefs(props)
        const handleSwitchChange = (val: string, row: any) => {
            qualityApi.switchRobot({robotNo: row.robotNo, enabled: val}).then(res => {
              if (!res.success) {
                message.error(res.message)
                return
              }
              if (val) {
                message.success("启用成功")
              } else {
                message.success("停用成功")
              }
              cardList.value = cardList.value.map(item => {
                if (item.robotNo === row.robotNo) {
                  item.enabled = val
                }
                return item
              })
            })
            .catch(err => {
              message.error(err.message)
            })
        }

        return {
            cardList,
            handleSwitchChange
        }
    },

    render() {
        const directives = [{name: 'loading', value: this.loading}]
        return (
            <div class={'quality-item-list'} {...{directives}}>
                <div class={'quality-item-list-box'}>
                {
                    this.cardList.map((item) => {
                        return (
                            <QualityItem data={item} key={item.robotNo} onChange={(val, value) => this.handleSwitchChange(val, value)} onEdit={(robotNo) => this.$emit('edit', robotNo)} onDelete={(robotNo) => this.$emit('delete', robotNo)} onGoDetail={(robotNo) => this.$emit('goDetail', robotNo)}/>
                        )
                    })
                }
                </div>
            </div>
        )
    }
})